<template>
    <Dashboard :menu="menu">
        <el-form label-width='110px' :model='formItem' :rules="rules" ref="formItem">
            <el-form-item label='名称' prop="name">
                <el-input v-model="formItem.name" style="width: 300px" placeholder="请输入优惠券名称" clearable></el-input>
            </el-form-item>
            <el-form-item label='图片'>
                <div class="upload-list" v-if="formItem.img_url">
                    <img :src="formItem.img_url">
                    <div class="upload-list-cover">
                        <i class="el-icon-edit" @click="uploadImg"></i>
                        <i class="el-icon-delete" @click="handleDel"></i>
                    </div>
                </div>
                <div @click='uploadImg' class='upload-img' v-else>
                    <i class='el-icon-upload'></i>
                </div>
                <!-- <el-row style="clear:both">最佳尺寸：375*187px</el-row> -->
            </el-form-item>
            <el-form-item label='发放数量'>
                <el-input-number v-model="formItem.num" :min="0" controls-position="right"></el-input-number>
                <span style="margin-left:10px;color:#aaa">数量为0表示无限制</span>
            </el-form-item>
            <el-form-item label='每人限领'>
                <el-input-number v-model="formItem.limit_num" :min="0" controls-position="right"></el-input-number>
                <span style="margin-left:10px;color:#aaa">数量为0表示无限制</span>
            </el-form-item>
            <el-form-item label='使用条件' prop="limit_price">
                <el-input-number v-model="formItem.limit_price" :min="0" controls-position="right" style="margin-right:10px"></el-input-number>
                <span>订单满 {{formItem.limit_price}} 元可用</span>
            </el-form-item>
            <el-form-item label='优惠金额' prop="price">
                <el-input-number v-model="formItem.price" :min="0" controls-position="right"></el-input-number>
            </el-form-item>
            <el-form-item label='起止时间' prop="timeRange">
                <el-date-picker v-model="formItem.timeRange" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label='状态'>
                <el-switch v-model='formItem.status'></el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type='primary' @click="ok('formItem')">确定</el-button>
                <el-button @click='back'>返回</el-button>
            </el-form-item>
        </el-form>
        <Upload :show="showUpload" @on-selected="selectImg" @on-cancel="cancelUpload"></Upload>
    </Dashboard>
</template>

<script>
import Dashboard from "./../../../components/Dashboard.vue";
export default {
    components: {
        Dashboard
    },
    data() {
        let checkLimitPrice = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("请正确输入使用条件"));
            } else if (value <= this.formItem.price) {
                return callback(new Error("订单金额应大于优惠金额"));
            } else {
                callback();
            }
        };
        let checkPrice = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("请正确输入使用金额"));
            } else if (value >= this.formItem.limit_price) {
                return callback(new Error("订单金额应大于优惠金额"));
            } else {
                callback();
            }
        };
        return {
            menu: [
                {
                    name: "优惠券",
                    icon: "icon-youhuiquan",
                    sub: [
                        {
                            name: "优惠券列表",
                            url: "/shop/coupon/coupon"
                        }
                    ]
                }
            ],
            showUpload: false,
            formItem: {
                id: 0,
                name: "",
                price: "",
                limit_price: "",
                limit_num: "",
                num: "",
                timeRange: [],
                started_at: "",
                ended_at: "",
                status: true
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入标题",
                        trigger: "change"
                    }
                ],
                limit_price: [
                    {
                        required: true,
                        validator: checkLimitPrice,
                        trigger: "change"
                    }
                ],
                price: [
                    {
                        required: true,
                        validator: checkPrice,
                        trigger: "change"
                    }
                ],
                timeRange: [
                    {
                        required: true,
                        message: "请选择起止时间",
                        trigger: "change"
                    }
                ]
            }
        };
    },
    async asyncData({ app, query }) {
        let data = {};
        if (query.id) {
            let config_data = await app.$axios.$get(
                `/api/shop/home/shop/plugin/coupon/info?id=${query.id}`
            );
            if (config_data && config_data.errmsg === "ok") {
                data.formItem = config_data.data;
                data.formItem.timeRange = [
                    config_data.data.started_at,
                    config_data.data.ended_at
                ];
                data.formItem.status = data.formItem.status ? true : false;
            }
            return data;
        } else {
            data.formItem = {
                id: 0,
                name: "",
                price: "",
                limit_price: "",
                limit_num: "",
                num: "",
                timeRange: [],
                started_at: "",
                ended_at: "",
                status: true
            };
            return data;
        }
    },
    methods: {
        //上传图片
        uploadImg() {
            this.showUpload = true;
        },
        selectImg(res) {
            this.showUpload = false;
            if (res.id > 0) {
                this.formItem.img_url = res.url;
            }
        },
        cancelUpload() {
            this.showUpload = false;
        },
        handleDel(index) {
            this.formItem.img_url = "";
        },
        ok(formItem) {
            this.$refs[formItem].validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        async submit() {
            let data = {
                id: this.formItem.id,
                name: this.formItem.name,
                img_url: this.formItem.img_url,
                price: this.formItem.price,
                limit_price: this.formItem.limit_price,
                num: this.formItem.num,
                limit_num: this.formItem.limit_num,
                status: this.formItem.status,
                started_at: this.format(this.formItem.timeRange[0]),
                ended_at: this.format(this.formItem.timeRange[1])
            };
            const res = await this.$axios.$post(
                "/api/shop/home/shop/plugin/coupon/add",
                data
            );
            if (res && res.errmsg === "ok") {
                this.$message.success({
                    type: "success",
                    message: "保存成功"
                });
                this.$router.push({
                    path: "/shop/coupon/coupon"
                });
            }
        },
        back() {
            this.$router.push({
                path: "/shop/coupon/coupon"
            });
        }
    }
};
</script>
